import { config } from './config';

interface HttpOption {
    url: string;
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    data?: Object | String | ArrayBuffer;
    headers?: Record<string, string>;
    params?: Record<string, string>; // 更具体的类型
}

export const http = (options: HttpOption): Promise<any> => new Promise((resolve) => {
    let url = config.apiBaseUrl + options.url;

    if (options.params != undefined) {
        let str = Object.keys(options.params)
            .map(item => {
				if ((options.params as any)[item]) {
					return `${encodeURIComponent(item)}=${encodeURIComponent((options.params as any)[item])}`;
				} else {
					return null
				}
			})
			.filter(item => item)
            .join('&');
        if (str) {
            url += (url.includes('?') ? '&' : '?') + str;
        }
    }

    const json: any = {
        url,
        header: {
            'tenant-id': config["tenant-id"],
			'tenant-type': 'app'
        },
        method: options.method || 'GET',
        dataType: 'json',
        responseType: 'text',
        sslVerify: false,
        complete: (res) => {
            if (res.statusCode === 200) {
                if (res.data.code === 0) {
                    resolve(res.data.data);
                } else {
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    });
                }
            } else if (res.statusCode === 401) {
                uni.removeStorageSync('user');
                uni.removeStorageSync('permission');
                uni.reLaunch({
                    url: '/pages/login/index'
                })
            } else if (res.statusCode === 404) {
                uni.showToast({
                    title: '接口不存在',
                    icon: 'none'
                });
                console.log("接口不存在", res.data.msg);
            } else {
                uni.showToast({
                    title: res.data.msg,
                    icon: 'none'
                });
                console.log(res.data.msg)
            }
        }
    };

    if (options.data) {
        json.data = options.data;
    }

    const user = uni.getStorageSync('user');
    if (user) {
        json.header['Authorization'] = `Bearer ${JSON.parse(user).accessToken}`;
    }

    if (options.headers) {
        json.header = {
            ...json.header,
            ...options.headers
        };
    }

    uni.request(json);
});